package org.fu.crowd.mvc.controller;

import org.fu.crowd.entity.Common;
import org.fu.crowd.entity.Menu;
import org.fu.crowd.service.api.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class MenuController {
    @Resource
    private MenuService menuService;


    /**
     * 获取所有结点并生成树结构
     * @return
     */
    @ResponseBody
    @RequestMapping("/menu/getWholeTree")
    public Common<Menu> getWholeTree(){
        //获取所有menu对象
        List<Menu> allMenu = menuService.getAll();
        //声明一个变量用来存储找到的根结点
        Menu root = null;
        //声明一个map集合用来存储父子关系
        Map<Integer, Menu> menuMap = new HashMap<>();
        for (Menu menu :allMenu) {
            Integer id = menu.getId();
            menuMap.put(id,menu);
        }
        for (Menu menu :allMenu){
            Integer pid = menu.getPid();
            if (pid==null){
                root = menu;
                continue;
            }
            Menu father = menuMap.get(pid);
            father.getChildren().add(menu);
        }
        return Common.successWithoutData(root);
    }








    /**
     *              保存结点
     * @return
     */
    @ResponseBody
    @RequestMapping("/menu/saveMenu")
    public Common<Menu> saveMenu(Menu menu){
        menuService.saveMenu(menu);
        return Common.successWithoutData();
    }











    /**
     *              修改结点
     * @return
     */
    @ResponseBody
    @RequestMapping("/menu/updateMenu")
    public Common<Menu> updateMenu(Menu menu){
        menuService.updateMenu(menu);
        return Common.successWithoutData();
    }







    /**
     *              删除结点
     * @return
     */
    @ResponseBody
    @RequestMapping("/menu/removeMenu")
    public Common<Menu> removeMenu(@RequestParam("id")Integer id){
        menuService.removeMenu(id);
        return Common.successWithoutData();
    }
}
